var appWxShareDirective = angular.module("appWxShareDirective",[]);
appWxShareDirective.directive("wxShare",function(appWxShareService,$location){
	return {
		template: "<div><div/>",
		restrice: "E",
		replace: true,
		controller:function($scope,$element,$attrs){
			appWxShareService.share();
			console.log('wxc');
		}
	}
})

appWxShareDirective.service("appWxShareService",['$http','$location',function($http,$location){
	var cururl  = location.href;
    cururl = cururl.replace(location.hash,'');
	console.log(cururl);
	this.share = function(){
	var  transFn = function(data) {
                return $.param(data);
           };
    var postCfg = {
                headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                transformRequest: transFn
            };
    var sc = document.querySelector("#wxsc");
    var flag = !!sc;
    if(!flag){
   	 	sc = document.createElement('SCRIPT');
    		document.body.appendChild(sc);  	 	
    }
	sc.src = "http://res.wx.qq.com/open/js/jweixin-1.0.0.js";    
    	var count = 5;
    		function share(){
    			console.log('loaded');
			$http.post("/lookup/index.php/Home/Sign/index",{url:cururl,t:new Date().getMilliseconds()},postCfg).success(function(data, status, headers, config) {
				console.log(angular.toJson(data));
		        wx.config({
		            debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
		            appId: data.appId, // 必填，公众号的唯一标识
		            timestamp: data.timestamp, // 必填，生成签名的时间戳
		            nonceStr: data.nonceStr, // 必填，生成签名的随机串
		            signature: data.signature,// 必填，签名，见附录1
		            jsApiList: [
		            'onMenuShareAppMessage',
		            'onMenuShareTimeline'
		            ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
		        });
		        var isDetail = location.hash.indexOf('home/detail')!=-1;
		        var title = document.querySelector(".start_name")?'见过'+document.querySelector(".start_name").innerHTML.trim()+'老师后,我的内心几乎是...':"扒一扒老师的故事、小爱好与口头禅，或者你还知道更多......";
		        var pic = document.querySelector(".start_headimg img")?document.querySelector(".start_headimg img").getAttribute("ng-src"):"http://"+location.hostname+"/meet/static/images/logo.png";
		        var sharetitle = isDetail?title:"扒一扒老师的故事、小爱好与口头禅，或者你还知道更多......";
		        var sharedesc =  '见过|扒一扒老师的故事、小爱好与口头禅，或者你还知道更多......';//isDetail?title:"见过|扒一扒老师的故事、小爱好与口头禅，或者你还知道更多......";
		        var shareimg = isDetail?pic:"http://"+location.hostname+"/meet/static/images/logo.png";
		        var shareurl = isDetail?location.href:"http://"+location.hostname;
		        var shareData = {
		            title: sharetitle,
		            desc: sharedesc,
		            link: shareurl,
		            imgUrl: shareimg,
		            success: function (res) {
		            },
		            cancel: function (res) { 
		            }
		          };		       
		       wx.ready(function () {
		          //好友
		          wx.onMenuShareAppMessage(shareData);
		          wx.onMenuShareTimeline(shareData);
		        });	
		      wx.error(function(res){
		      		if(count-- >0 ){
			      		var data = {'res':res,'shareData':shareData,'count':count};
			            $http.post("/lookup/index.php/Home/Sign/logError",{data:angular.toJson(data)},postCfg);
//			            location.reload(true);
			           console.log(data);
			            share();
		      		}else{
			      		var data = {'res':res,'shareData':shareData,'count':count,'note':'放弃了！','absUrl':$location.absUrl()};
			      		console.log(data);
			            $http.post("/lookup/index.php/Home/Sign/logError",{data:angular.toJson(data)},postCfg);
//			            $location.path($location..absUrl());
		      		}

		      });
		    }).error(function(data, status, headers, config) {
		//		alert('啊呀，分享配置失效啦，容我再试一次！');
		  });      			
    		}
    		
    		sc.onload = function(){  
    			share();
    		}

		
	};

	
}])
